﻿using SuperSocket;
using SuperSocket.ProtoBase;
using System.Text;

namespace EchoServer
{
    internal class Program
    {
        static CancellationTokenSource TokenSource = new CancellationTokenSource();

        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            //var host = CreateHost();
            _ = StartAsync();

            do
            {
                if (Console.ReadKey().Key == ConsoleKey.Q)
                {
                    Console.WriteLine("停止服务了");
                    TokenSource.Cancel();
                    break;
                }
            } while (!TokenSource.IsCancellationRequested);

            Console.WriteLine("退出程序了");
        }

        static async ValueTask StartAsync()
        {
            var host = CreateHost();
            await host.StartAsync();

            do
            {
                await Task.Delay(100);
            } while (!TokenSource.IsCancellationRequested);

            await Console.Out.WriteLineAsync("线程取消了");
            await host.StopAsync();
            await Console.Out.WriteLineAsync("停止了");
            //await host.StopAsync(TokenSource.Token);
        }

        static IServer CreateHost()
        {
            return SuperSocketHostBuilder.Create<StringPackageInfo, CommandLinePipelineFilter>()
                 .UseSessionHandler(session =>
                 {
                     Console.WriteLine($"{session.SessionID} {DateTime.Now} Connected");
                     return ValueTask.CompletedTask;
                 }, (session, args) =>
                 {
                     Console.WriteLine($"{session.SessionID} {DateTime.Now} Closed({args.Reason})");
                     return ValueTask.CompletedTask;
                 })
                 .UsePackageHandler((session, package) =>
                 {
                     return session.SendAsync(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
                 })
                 .ConfigureSuperSocket(options =>
                 {
                     options.AddListener(new ListenOptions
                     {
                         Ip = "127.0.0.1",
                         Port = 13690
                     });
                 }).BuildAsServer();
                 //.Build();
        }
    }

}